package com.wsh.archive.service.facade;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.chain.Catalog;
import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
import org.apache.commons.chain.config.ConfigParser;
import org.apache.commons.chain.impl.CatalogFactoryBase;

public final class ArchiveFacade {

	private static ArchiveFacade instance = null;
	
	private ArchiveFacade() {
		super();
	}
	
	public static ArchiveFacade getInstance() {
		if (instance == null)
            instance = new ArchiveFacade();
        return instance;
	}

	private Catalog catalog = null;
	
	public Context executeCommand(Context ctx, String service) {
		
		try {			
			catalog = parseConfigFile();			
			Command command = catalog.getCommand(service);
			command.execute(ctx);		
			Logger.getLogger("COMMAND: " + service + "executada com sucesso!");
		} catch (Exception e) {
			Logger.getLogger("com.wsh.archive.service.facade.ArchiveFacade: executeCommand").log(Level.SEVERE, e.getMessage());
		}		
		return ctx;
	}
	
	protected Catalog parseConfigFile() {

		ConfigParser parser = new ConfigParser();
		String fileLocation = "/chain-config.xml";

		try {
			parser.parse(this.getClass().getResource(fileLocation));
		} catch (Exception e) {
			Logger.getLogger("com.wsh.archive.service.facade.ArchiveFacade: parseConfigFile").log(Level.SEVERE, e.getMessage());
		}
		return CatalogFactoryBase.getInstance().getCatalog();
	}
	
}